import {
  getAccessTokenStorage, setAccessTokenStorage,
  getRefreshTokenStorage, setRefreshTokenStorage
} from '@/libs/storage'
import { API_REFRESHTOKEN } from '@/service/account'

const state = {
  accessToken: getAccessTokenStorage(),
  refreshToken: getRefreshTokenStorage()
}

const getters = {
  tokenHeader (state) {
    return `Bearer ${state.accessToken}`
  }
}

const mutations = {
  setToken (state, token) {
    state.accessToken = token['access_token']
    state.refreshToken = token['refresh_token']
  }
}

const actions = {
  // 保存token
  saveToken ({ commit }, data) {
    let { access_token, refresh_token } = data
    setAccessTokenStorage(access_token)
    setRefreshTokenStorage(refresh_token)
    commit('setToken', { access_token, refresh_token })
  },
  refreshToken ({ dispatch, state }) {
    let reqData = {
      refresh_token: state.refreshToken,
      grant_type: 'grant_type'
    }
    API_REFRESHTOKEN(reqData).then(resData => {
      let {
        access_token,
        refresh_token,
        userId,
        nickname,
        headImageUrl,
        phoneNum
      } = resData
      dispatch('saveToken', { access_token, refresh_token }) // 保存token到store
      dispatch('saveUserInfo', {
        nickname,
        userId,
        phoneNum,
        headImageUrl
      }) // 获取用户信息
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
